package com.huyn.baseframework.net;

import android.content.Intent;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.huyn.baseframework.model.BaseModel;
import com.huyn.baseframework.utils.Constant;

import org.apache.http.conn.ConnectTimeoutException;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by huyaonan on 16/10/8.
 */
public class BFJSONRequest<T extends BaseModel> extends Request<T> {

    private HashMap<String, String> reqMap;

    private Class<T> clazz;

    public BFJSONRequest(Class<T> clazz, HashMap<String, String> params, Response.Listener<T> listener) {
        super(Method.POST, OpenApi.getRouter(), listener);
        this.clazz = clazz;

        params.put("format", "json");
        replaceMethod(params);
        reqMap = ParamParser.ParserParamsAPI(params);

        setShouldCache(false);
        setAllowRetry(false);
    }

    /**
     * 测试服替换一些方法
     * @param params
     */
    private void replaceMethod(HashMap<String, String> params) {
//        if(OpenApi.getRouter().equalsIgnoreCase(OpenApi.ROUTER_TEST)) {
            if (params.containsKey("method")) {
                String value = params.get("method");
                if (value.equalsIgnoreCase("com.aube.app.template.data"))
                    params.put("method", "com.aube.app.v2.template.data");
                else if (value.equalsIgnoreCase("com.aube.app.model.data"))
                    params.put("method", "com.aube.app.v2.model.data");
                else if (value.equalsIgnoreCase("com.aube.app.model.data.detail"))
                    params.put("method", "com.aube.app.v2.model.data.detail");
            }
//        }
    }

    public BFJSONRequest(String url, Class<T> clazz, Response.Listener<T> listener) {
        super(Method.GET, url, listener);
        this.clazz = clazz;

        setShouldCache(false);
        setAllowRetry(false);
    }

    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> customizedHeader = new HashMap<String, String>();
        customizedHeader.put("Accept-Encoding", "gzip");
        customizedHeader.put("Connection", "Keep-Alive");
        return customizedHeader;
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String parsed = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
//			if(Constant.DEBUG)
//				Log.i("VOLLEYREQUEST", parsed);

            if (clazz != null) {
                Gson gson = new Gson();
                T feed = gson.fromJson(parsed, clazz);

//				if(loadCache && StringUtils.isNotBlank(cacheKey) && contxt != null && saveTime > 0 && feed.success()){
//					ACache.get(contxt).put(cacheKey, feed, saveTime);
//				}
                return Response.success(feed, HttpHeaderParser.parseCacheHeaders(response));
            } else {
                return Response.error(new ParseError("解析错误"));
            }
        } catch(IOException e){
            e.printStackTrace();
            return Response.error(new ParseError("网络连接错误"));
        } catch (Exception e) {
            e.printStackTrace();
            return Response.error(new ParseError("网络连接错误"));
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            System.gc();
            return Response.error(new ParseError("解析错误"));
        }
    }

    public Map<String, String> getParams() throws AuthFailureError {
        return reqMap;
    }

    @Override
    public void deliverResponse(T response) {
        if(mListener != null)
            mListener.onResponse(response);
        //用户信息失效
        if(OpenApi.ERROR_CODE_FOR_LOGIN.equalsIgnoreCase(response.code)) {
            contxt.sendBroadcast(new Intent(Constant.MEMBERENCODE_ILLEGAL));
        }
    }

    @Override
    protected VolleyError parseNetworkError(VolleyError volleyError) {
        Throwable throwable = volleyError.getCause();
        if(throwable instanceof ConnectTimeoutException){
            return new VolleyError("网络连接超时",throwable);
        }else if(throwable instanceof UnknownHostException){
            return new VolleyError("无法连接网络",throwable);
        }else if(throwable instanceof IOException){
            return new VolleyError("网络异常",throwable);
        }
        return super.parseNetworkError(volleyError);
    }

}